<template>
  <div>
        <!-- 面包削 -->
  <el-breadcrumb>
      <el-breadcrumb-item :to = "{path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片视图 -->
  <el-card>
  <!-- alert 提示栏-->
    <el-alert
    title="请添加商品" type="info" center show-icon :closable="false"> </el-alert>
    <!-- 步骤条 -->
        <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
        </el-steps>
        <!-- 验证表单 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <!-- tab栏 -->
        <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave"
        @tab-click="tabclicked">
        <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item> 
            <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 级联选择器 -->
            <el-form-item label="商品分类" >
                <el-cascader  v-model="addForm.goods_cat" :options="catelist" :props="cateProps" props.expandTrigger="hover"
                 @change="handleChange"></el-cascader>
            </el-form-item>

        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyTabdata" :label="item.attr_name" :key="item.attr_id">
                <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals" >
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
            </el-checkbox-group>
``
            </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableDate" :key="item.attr_id">
                <el-input :value="item.attr_vals"></el-input>
            </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
            <el-upload :action="uploadUrl" :on-preview="handlePreview" :headers="headerObj" :on-success="handleSuccess" :on-remove="hanldeRemove" list-type="picture">
            <el-button size="small" type="primary" >点击上传</el-button>
  
</el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="buttonAdd" @click="add">提交数据</el-button>
        </el-tab-pane>
        </el-tabs>
        </el-form>
    </el-card>

<!-- 切换显示图片框 -->
    <el-dialog title="图片" :visible.sync="preViewVisible" width="50%">
    <img :src="preViewUrl" class="preViewDialog">
    </el-dialog>
  </div>
</template>

<script>
// 引入lodash插件
import _ from 'lodash'
export default {
    data(){
        return {
            activeIndex:'0',
             // Add表单数据
            addForm:{
                goods_name:'',
                goods_price: 0,
                goods_weight: 0,
                goods_number: 0,
                goods_cat:[],
                // 保存图片地址
                pics:[],
                //商品描述内容
                goods_introduce:'',
                // 提交数据包含
                attrs:[]

            },
            // 表单验证规则
            addFormRules:{
                goods_name:[{
                    required:true,message:'请输入',tiggle:blur
                }],
                goods_price:[{
                    required:true,message:'请输入价格',tiggle:blur
                }],
                goods_weight:[{
                    required:true,message:'请输入重量',tiggle:blur
                }],
                goods_number:[{
                    required:true,message:'请输入数量',tiggle:blur
                }],
                goods_cat:[{
                    required:false,message:'请选择分类',tiggle:blur
                }]
            },
            // 商品分类列表数据
            catelist:[],
            // 级联选择器的显示数据
            cateProps:{
                label:'cat_name',
                value:'cat_id',
                children:'children'
            },
            // 动态参数数据
            manyTabdata:[],
            // 静态属性
            onlyTableDate:[],
            // URL保存为字符数据 
            uploadUrl:'http://127.0.0.1:8888/api/private/v1/upload',
            // 保存请求头证书对象
            headerObj:{
                Authorization:window.sessionStorage.getItem('token')
            },
            // 储存图片地址
            preViewUrl:'',
            // 切换显示图片框
            preViewVisible:false,

        }
    },
    created(){
        // 获取商品
        this.getCateList()



    },
    methods:{
         // 获取商品
         async getCateList(){
            const {data : res} = await this.$http.get(`categories`)
            if(res.meta.status !== 200){
                return this.$message.error('获取数据失败')
            }
            this.catelist = res.data
            
         },
        //  级联选择器动作
        handleChange(){
            if(this.addForm.goods_cat.length !== 3){
                this.addForm.goods_cat = []
            }
        },
        //判断切换时的进程
        beforeTabLeave(activeName,oldActiveName){
            if(oldActiveName === '0' && this.addForm.goods_cat.length !== 3){
                this.$message.error('请选择三级分类')
                return false
            }
        },
        // 切换Tab标签
       async tabclicked(){
            if(this.activeIndex === '1'){
                const {data : res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                    params:{ sel : 'many' }
                })
                if(res.meta.status !== 200){
                    return this.$message.error('获取失败')
                }
                // 循环data里数据
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
                })
                this.manyTabdata = res.data
            }
            // 获取商品属性
            else if(this.activeIndex === '2'){
              const {data :res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                    params:{ sel: 'only'}
                })
                if(res.meta.status !== 200){
                    return this.$message.error('获取数据失败')
                }this.onlyTableDate = res.data
            }
            },
            // 图片放大事件
            handlePreview(file){
                this.preViewUrl = file.response.data.url
                this.preViewVisible = true

            },
            // 图片删除事件
            hanldeRemove(file){
                const addres = file.response.data.tmp_path
                const i = this.addForm.pics.findIndex( x => x.pic === addres)
                this.addForm.pics.splice(i,1)
                console.log(this.addForm)


            },
            // 图片提交成功返回
            handleSuccess(response){
                const picsInfo = { pics : response.data.tmp_path}
                this.addForm.pics.push(picsInfo)
            },
            // 提交数据
            add(){
                this.$refs.addFormRef.validate(async valid =>{
                    if(!valid){
                        return this.$message.error('请完整填写')
                    }
                    const form = _.cloneDeep(this.addForm) 
                    form.goods_cat = form.goods_cat.join(',')
                    // 动态参数的转换
                    this.manyTabdata.forEach(item => {
                        const manyInfo = {
                            attr_id:item.attr_id,
                            attr_value:item.attr_vals.join(',')
                        }
                        this.addForm.attrs.push(manyInfo)
                    })
                    // 静态属性的转换
                    this.onlyTableDate.forEach(item =>{
                        const onlyInfo = {
                            attr_id:item.attr_id,
                            attr_value:item.attr_vals
                        }
                        this.addForm.attrs.push(onlyInfo)
                    })
                    form.attrs = this.addForm.attrs
                    const {data :res} = await this.$http.post(`goods`,form)
                    if(res.meta.status !== 201){
                        return this.$message.error('创建失败')
                    }this.$message.success('创建成功')
                    this.$router.push(`/goods`)
                })
            }

        },

    computed:{
        cateId(){
            if(this.addForm.goods_cat.length ===3){
                return this.addForm.goods_cat[2]
            }
            return null
        }
    }

}
</script>

<style scoped lang="less">
.el-checkbox {
    margin:0 10px 0 0 !important;
}
.preViewDialog {
    width: 100%;
}
.buttonAdd {
    margin-top: 15px;
}

</style>

